//
//  PicturePickerController.swift
//  照片选择
//
//  Created by 梁智 on 15/12/4.
//  Copyright © 2015年 lzfree. All rights reserved.
//

import UIKit

/// 可重用标识符
private let PicturePickerViewId = "PicturePickerViewId"
/// 最大选择照片数量
private let PicturePickerMaxCount = 3

class PicturePickerController: UICollectionViewController {

    /// 配图数组
    lazy var pictures = [UIImage]()
    
    /// 当前选中照片索引
    private var selectedIndex = 0
    
    // MARK: - 构造函数
    init() {
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册可重用 cell
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerViewId)

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }


    private class PicturePickerLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            let count: CGFloat = 4
            let margin = UIScreen.mainScreen().scale * 4
            
            let w = (collectionView!.bounds.width - (count + 1) * margin) / count
            itemSize = CGSize(width: w, height: w)
            
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        }
    }
}

// MARK: - UICollectionViewDataSource
extension PicturePickerController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerViewId, forIndexPath: indexPath) as! PicturePickerCell
        
        cell.pictureDelegate = self
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        
        return cell
        
    }
}

// MARK: - PicturePickerCellDelegate
// 如果协议是私有的，那么协议方法也必须是私有的
extension PicturePickerController: PicturePickerCellDelegate {
    
    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
        // 判断是否允许访问相册
        /**
        PhotoLibrary            保存的照片(可以删除) + 同步的照片(不允许删除)
        SavedPhotosAlbum        保存的照片/屏幕截图/拍照
        */
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("不允许访问照片库")
            return
        }
        
        // 记录选中照片的索引
        selectedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
        
        // 访问相册
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        if indexPath.item >= pictures.count {
            return
        }
        
        pictures.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
    }
}


// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PicturePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    /// 照片选择完成
    ///
    /// - parameter picker: 照片选择控制器
    /// - parameter info:   info 字典
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scaleImage = image.scaleToWidth(600)
        
        // 将图像添加到数组
        if selectedIndex < pictures.count {
            pictures[selectedIndex] = scaleImage
        } else {
            pictures.append(scaleImage)
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}


/// PicturePickerCellDelegate 代理
/// 如果协议中包含 optional 的函数，协议需要使用 @objc 修饰
@objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {
    
    /// 添加照片
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    /// 删除照片
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}


// MARK: - 照片选择 Cell - private修饰类，内部的一切方法和属性，都是私有的
private class PicturePickerCell: UICollectionViewCell {
    
    /// 照片选择代理
    weak var pictureDelegate: PicturePickerCellDelegate?
    
    /// 照片图像
    private var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            closeButton.hidden = (image == nil)
        }
    }
    
    // MARK: - 监听方法
    @objc private func addPicture() {
        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    
    @objc private func removePicture() {
        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置控件
    private func setupUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(closeButton)
        
        addButton.frame = bounds
        closeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        closeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
    // MARK: - 懒加载控件
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    
    private lazy var closeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
}